/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mapfinal.server.auth.service.impl;

import java.util.List;

import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.lambkit.common.service.LambkitModelServiceImpl;
import com.lambkit.common.util.EncryptUtils;
import com.lambkit.common.util.StringUtils;
import com.lambkit.core.aop.AopKit;
import com.lambkit.db.sql.column.Example;
import com.mapfinal.server.MapfinalServer;
import com.mapfinal.server.auth.UserService;
import com.mapfinal.server.auth.model.AuthOrganization;
import com.mapfinal.server.auth.model.RoleUser;
import com.mapfinal.server.auth.model.Role;
import com.mapfinal.server.auth.model.UserOrganization;
import com.mapfinal.server.auth.model.User;

/**
 * @author yangyong 
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date 2020-09-23
 * @version 1.0
 * @since 1.0
 */
public class UserServiceImpl extends LambkitModelServiceImpl<User> implements UserService {
	
	private User DAO = null;
	
	public User dao() {
		if(DAO==null) {
			DAO = AopKit.singleton(User.class);
		}
		return DAO;
	}
	
	public User getUser(String name, String pass) {
		Example example = User.sql().andUserLoginEqualTo(name).andUserPassEqualTo(pass).example();
		return findFirst(example);
	}
	
	public User findByUuid(String uuid) {
		Example example = User.sql().andUuidEqualTo(uuid).example();
		return findFirst(example);
	}
	
	@Override
	public User findByUserNameCache(String name) {
		// TODO Auto-generated method stub
		return dao().findFirstByCache(getTableName(), name, "select * from " + getTableName() + " where user_login=?", name);
	}
	
	public User findByUserName(String name) {
		if(StrKit.isBlank(name)) return null;
		Example example = User.sql().andUserLoginEqualTo(name).example();
		return findFirst(example);
		//return dao().findFirstByCache(getTableName(), name, "select * from " + getTableName() + " where user_login=?", name);
	}
	
	@Override
	public User findByLoginName(String name) {
		// TODO Auto-generated method stub
		if(StringUtils.isEmail(name)) {
			return findByEmail(name);
        } else if(StringUtils.isMobileNumber(name)) {
        	return findByPhone(name);
        } else {
        	return findByUserName(name);
        }
	}

	@Override
	public User findByEmail(String name) {
		// TODO Auto-generated method stub
		if(StrKit.isBlank(name)) return null;
		Example example = User.sql().andUserEmailEqualTo(name).example();
		return findFirst(example);
	}

	@Override
	public User findByPhone(String name) {
		// TODO Auto-generated method stub
		if(StrKit.isBlank(name)) return null;
		Example example = User.sql().andUserPhoneEqualTo(name).example();
		return findFirst(example);
	}
	
	public String getPasswordSecurity(String pass) {
		return getPasswordMD5(pass);
	}
	/**
	 * 加密
	 * @param password
	 * @return
	 */
	public String getPasswordMD5(String password) {
		if (!StringUtils.hasText(password))
			return null;
		return EncryptUtils.md5WithPrefix(password);
	}
	
	/**
	 * 用户名是否已被注册
	 */
	public boolean isUserNameExists(String userName) {
		userName = userName.toLowerCase().trim();
		return MapfinalServer.db().queryInt("select id from mf_user where user_login = ? limit 1", userName) != null;
	}
	
	/**
	 * 昵称是否已被注册，昵称不区分大小写，以免存在多个用户昵称看起来一个样的情况
	 *
	 *  mysql 的 where 字句与 order by 子句默认不区分大小写，区分大小写需要在
	 *  字段名或字段值前面使用 binary 关键字例如：
	 *  where nickName = binary "jfinal" 或者 where binary nickName = "jfinal"，前者性能要高
	 *
	 *  为了避免不同的 mysql 配置破坏掉 mysql 的 where 不区分大小写的行为，这里在 sql 中使用
	 *  lower(...) 来处理，参数 nickName 也用 toLowerCase() 方法来处理，再次确保不区分大小写
	 */
	public boolean isNickNameExists(String nickName) {
		nickName = nickName.toLowerCase().trim();
		return MapfinalServer.db().queryInt("select id from mf_user where lower(user_nicename) = ? limit 1", nickName) != null;
	}
	
	/**
	 * 添加角色
	 */
	public Ret addRole(int accountId, int roleId) {
		RoleUser ru = new RoleUser().set("user_id", accountId).set("role_id", roleId);
		boolean flag = ru.save();
		return flag ? Ret.ok("msg", "添加角色成功") : Ret.fail("msg", "添加角色失败");
	}

	/**
	 * 删除角色
	 */
	public Ret deleteRole(int accountId, int roleId) {
		int r = MapfinalServer.db().delete("delete from mf_role_user where user_id=? and role_id=?", accountId, roleId);
		return r>0 ? Ret.ok("msg", "删除角色成功") : Ret.fail("msg", "删除角色失败");
	}
	
	/**
	 * 标记出 account 拥有的角色
	 * 未来用 role left join account_role 来优化
	 */
	public void markAssignedRoles(User account, List<Role> roleList) {
		String sql = "select user_id from mf_role_user where user_id=? and role_id=? limit 1";
		for (Role role : roleList) {
			Integer accountId = MapfinalServer.db().queryInt(sql, account.getId(), role.getId());
			if (accountId != null) {
				// 设置 assigned 用于界面输出 checked
				role.put("assigned", true);
			}
		}
	}

	@Override
	public void markAssignedOrganizations(User account, List<AuthOrganization> orgList) {
		// TODO Auto-generated method stub
		String sql = "select * from mf_user_organization where user_id=? and organization_id=? limit 1";
		for (AuthOrganization org : orgList) {
			UserOrganization uo = UserOrganization.service().dao().findFirst(sql, account.getId(), org.getId());
			if (uo != null) {
				// 设置 assigned 用于界面输出 checked
				org.put("assigned", true);
				org.put("jobs", uo.getJobs());
				org.put("jobId", uo.getJobId());
				account.put("orgId", uo.getOrganizationId());
				account.put("orgName", org.getName());
				account.put("jobId", uo.getJobId());
				account.put("jobs", uo.getJobs());
				
			}
		}
	}

	@Override
	public Ret setOrganization(Long accountId, Integer orgId, Integer jobId, String jobs) {
		// TODO Auto-generated method stub
		if(accountId==null || orgId==null) {
			return Ret.fail("msg", "参数错误");
		}
		UserOrganization ru = UserOrganization.service().findFirst(UserOrganization.sql().andUserIdEqualTo(accountId).example());
		boolean flag = false;
		if(ru==null) {
			ru = new UserOrganization();
			ru.setUserId(accountId);
			ru.setOrganizationId(orgId);
			ru.setJobId(jobId);
			ru.setJobs(jobs);;
			flag = ru.save();
		} else {
			int i = MapfinalServer.db().update("update mf_user_organization set job_id=?, jobs=?, organization_id=?  where user_id=?", jobId, jobs, orgId, accountId);
			flag = i > 0 ? true : false;
		}
		return flag ? Ret.ok("msg", "设置公司成功") : Ret.fail("msg", "设置公司失败");
	}

	@Override
	public Ret deleteOrganization(Long accountId, Integer orgId) {
		// TODO Auto-generated method stub
		int r = MapfinalServer.db().delete("delete from mf_user_organization where user_id=? and organization_id=?", accountId, orgId);
		return r>0 ? Ret.ok("msg", "删除公司成功") : Ret.fail("msg", "删除公司失败");
	}
	
}
